import sys
import os
import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database

class FeePayment:
    def __init__(self):
        self.db = Database()
    
    def pay_fee(self, fee_id):
        """
        缴纳指定的费用
        
        参数:
            fee_id (int): 费用记录ID
        
        返回:
            bool: 缴费成功返回True，否则返回False
        """
        try:
            # 验证输入
            try:
                fee_id = int(fee_id)
            except ValueError:
                print("错误：费用ID必须是数字")
                return False
            
            # 连接数据库
            self.db.connect()
            
            # 检查费用记录是否存在
            self.db.cursor.execute(
                """SELECT f.id, f.fee_type, f.amount, f.payment_status, d.building, d.room_number 
                FROM fee f 
                JOIN dormitory d ON f.dormitory_id = d.id 
                WHERE f.id = ?""",
                (fee_id,)
            )
            fee = self.db.cursor.fetchone()
            if not fee:
                print(f"错误：ID为 {fee_id} 的费用记录不存在")
                self.db.close()
                return False
            
            # 检查是否已缴费
            if fee[3] == 'paid':
                print(f"错误：ID为 {fee_id} 的费用已经缴纳")
                self.db.close()
                return False
            
            # 更新缴费状态
            payment_date = datetime.datetime.now().strftime("%Y-%m-%d")
            self.db.cursor.execute(
                "UPDATE fee SET payment_status = 'paid', payment_date = ? WHERE id = ?",
                (payment_date, fee_id)
            )
            self.db.conn.commit()
            
            print(f"成功：宿舍 {fee[4]}-{fee[5]} 的{fee[1]}费用 {fee[2]}元 已缴纳，缴费日期：{payment_date}")
            return True
        except Exception as e:
            print(f"错误：缴纳费用时发生错误 - {str(e)}")
            return False
        finally:
            self.db.close()
    
    def pay_dormitory_fees(self, dormitory_id, fee_type=None):
        """
        缴纳指定宿舍的所有未缴费用或指定类型的费用
        
        参数:
            dormitory_id (int): 宿舍ID
            fee_type (str, optional): 费用类型，如果指定则只缴纳该类型的费用
        
        返回:
            int: 成功缴纳的费用数量
        """
        try:
            # 验证输入
            try:
                dormitory_id = int(dormitory_id)
            except ValueError:
                print("错误：宿舍ID必须是数字")
                return 0
            
            # 连接数据库
            self.db.connect()
            
            # 检查宿舍是否存在
            self.db.cursor.execute(
                "SELECT building, room_number FROM dormitory WHERE id = ?",
                (dormitory_id,)
            )
            dormitory = self.db.cursor.fetchone()
            if not dormitory:
                print(f"错误：ID为 {dormitory_id} 的宿舍不存在")
                self.db.close()
                return 0
            
            building, room_number = dormitory
            
            # 构建查询SQL
            sql = "SELECT id, fee_type, amount FROM fee WHERE dormitory_id = ? AND payment_status = 'unpaid'"
            params = [dormitory_id]
            
            # 如果指定了费用类型，则只缴纳该类型的费用
            if fee_type:
                sql += " AND fee_type = ?"
                params.append(fee_type)
            
            # 查询未缴费记录
            self.db.cursor.execute(sql, params)
            fees = self.db.cursor.fetchall()
            
            if not fees:
                print(f"宿舍 {building}-{room_number} 没有{fee_type+'类型的' if fee_type else ''}未缴费记录")
                self.db.close()
                return 0
            
            # 更新缴费状态
            payment_date = datetime.datetime.now().strftime("%Y-%m-%d")
            count = 0
            total_amount = 0
            
            for fee in fees:
                fee_id, fee_type, amount = fee
                self.db.cursor.execute(
                    "UPDATE fee SET payment_status = 'paid', payment_date = ? WHERE id = ?",
                    (payment_date, fee_id)
                )
                count += 1
                total_amount += amount
                print(f"缴纳{fee_type}费用：{amount}元")
            
            self.db.conn.commit()
            print(f"成功：宿舍 {building}-{room_number} 共缴纳 {count} 笔费用，总金额：{total_amount}元，缴费日期：{payment_date}")
            return count
        except Exception as e:
            print(f"错误：缴纳费用时发生错误 - {str(e)}")
            return 0
        finally:
            self.db.close()

# 如果直接运行此文件，提供命令行界面
if __name__ == "__main__":
    payment = FeePayment()
    
    print("===== 宿舍费用缴纳 =====")
    print("1. 缴纳指定费用")
    print("2. 缴纳宿舍所有未缴费用")
    print("3. 缴纳宿舍指定类型的费用")
    
    choice = input("请选择操作 (1-3): ")
    
    if choice == '1':
        try:
            fee_id = input("请输入费用记录ID: ")
            payment.pay_fee(fee_id)
        except Exception as e:
            print(f"操作失败：{str(e)}")
    
    elif choice == '2':
        try:
            dormitory_id = input("请输入宿舍ID: ")
            payment.pay_dormitory_fees(dormitory_id)
        except Exception as e:
            print(f"操作失败：{str(e)}")
    
    elif choice == '3':
        try:
            dormitory_id = input("请输入宿舍ID: ")
            fee_type = input("请输入费用类型（如水费、电费、住宿费）: ")
            payment.pay_dormitory_fees(dormitory_id, fee_type)
        except Exception as e:
            print(f"操作失败：{str(e)}")
    
    else:
        print("无效的选择")